<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus08.html">Previous Chapter</a>
    <li> <a href="cplusplus10.html">Next Chapter</a>
</ul>
<hr>
<a name="OperatorOverloading"></a><a name="l143"></a>
<h1>Chapter 9: More Operator Overloading</h1>
<a name="overloading"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="overloading/more"></a>Having covered the <a name="an1166"></a>
overloaded assignment operator in chapter <a href="cplusplus07.html#MEMORY">7</a>,
and having shown several examples of other overloaded operators as well (i.e.,
the insertion and extraction operators in chapters <a href="cplusplus03.html#FirstImpression">3</a> and
<a href="cplusplus05.html#IOStreams">5</a>), we will now take a look at several other interesting examples
of <a name="an1167"></a>
operator overloading.
<p>
<a name="OPERATORINDEX"></a><a name="l144"></a>
<h2>9.1: Overloading `operator[]()'</h2>
<a name="overloading/array"></a>As our next example of operator overloading, we present a class
operating on an array of <code>int</code>s. Indexing the array elements occurs with
the standard array operator <code>[]</code>, but additionally the class checks for
<a name="an1168"></a>
boundary overflow. Furthermore, the <a name="an1169"></a>
index operator (<a name="an1170"></a>
<code>operator[]()</code>) is
interesting in that it both <em>produces</em> a value and <em>accepts</em> a value, when
used, respectively, as a <a name="an1171"></a>
<em>right-hand value</em> (<a name="an1172"></a>
<em>rvalue</em>) and a
    <a name="an1173"></a>
<em>left-hand value</em> (<a name="an1174"></a>
<em>lvalue</em>) in expressions.
    Here is an example showing the use of the class:
        <pre>
    int main()
    {
        IntArray x(20);                 // 20 ints

        for (int i = 0; i &lt; 20; i++)
            x[i] = i * 2;               // assign the elements

        for (int i = 0; i &lt;= 20; i++)   // produces boundary overflow
            cout &lt;&lt; "At index " &lt;&lt; i &lt;&lt; ": value is " &lt;&lt; x[i] &lt;&lt; endl;
    }
</pre>
    First, the constructor is used to create an object containing 20
<code>int</code>s. The elements stored in the object can be assigned or retrieved: the
first <code>for</code>-loop assigns values to the elements using the index operator,
the second <code>for</code>-loop retrieves the values, but will also produce a run-time
error as the non-existing value <code>x[20]</code> is addressed. The <code>IntArray</code> class
interface is:
        <pre>
    class IntArray
    {
        int     *d_data;
        unsigned d_size;

         public:
            IntArray(unsigned size = 1);
            IntArray(IntArray const &amp;other);
            ~IntArray();
            IntArray const &amp;operator=(IntArray const &amp;other);

                                                // overloaded index operators:
            int &amp;operator[](unsigned index);                // first
            int const &amp;operator[](unsigned index) const;    // second
        private:
            void boundary(unsigned index) const;
            void copy(IntArray const &amp;other);
            int &amp;operatorIndex(unsigned index) const;
    };
</pre>
    This class has the following characteristics:
    <ul>
    <li> One of its constructors has an <code>size_t</code> parameter having a
default argument value, specifying the number of <code>int</code> elements in the
object.
    <li> The class internally uses a pointer to reach allocated memory.
Hence, the necessary tools are provided: a copy constructor, an overloaded
assignment operator and a destructor.
    <li> Note that there are two overloaded index operators. Why are there
    two of them ?
<p>
The first overloaded index operator allows us to reach and modify the
elements of non-constant <code>IntArray</code> objects.  This overloaded operator has
as its prototype a function that returns <em>a reference</em> to an <code>int</code>. This
allows us to use expressions like <code>x[10]</code> as <em>rvalues</em> <em>or</em>
<em>lvalues</em>.
<p>
We can therefore use the same function to retrieve and to assign values.
Furthermore note that the return value of the overloaded array operator is
<em>not</em> an <code>int const &amp;</code>, but rather an <code>int &amp;</code>. In this situation we
don't use <code>const</code>, as we must be able to change the element we want to
access, when the operator is used as an lvalue.
<p>
However, this whole scheme fails if there's nothing to assign. Consider
the situation where we have an <code>IntArray const stable(5)</code>. Such an object is
a <em>const</em> object, which cannot be modified. The compiler detects this and
will refuse to compile this object definition if only the first overloaded
index operator is available. Hence the second overloaded index operator. Here
the return-value is an <code>int const &amp;</code>, rather than an <code>int &amp;</code>, and the
member-function itself is a <code>const</code> member function. This second form of the
overloaded index operator is not used with <em>non-</em><code>const</code> objects, but it's
only used with <code>const</code> objects. It is used for <a name="an1175"></a>
value-retrieval, not for
value-assignment, but that is precisely what we want, using <code>const</code>
objects. Here, members are overloaded only by their <code>const</code> attribute. This
form of function overloading was introduced earlier in the Annotations
(sections <a href="cplusplus02.html#FunctionOverloading">2.5.11</a> and <a href="cplusplus06.html#ConstFunctions">6.2</a>).
<p>
Also note that, since the values stored in the <code>IntArray</code> are primitive
values of type <code>int</code>, it's ok to use <a name="an1176"></a>
value return types.  However, with
objects one usually doesn't want the extra copying that's implied with value
return types. In those cases <a name="an1177"></a>
<code>const &amp;</code> return values are preferred for
<code>const</code> member functions. So, in the <code>IntArray</code> class an <code>int</code> return
value could have been used as well. The second overloaded index operator would
then use the following prototype:
        <pre>
    int IntArray::operator[](int index) const;
</pre>
    <li> As there is only one pointer data member, the destruction of the
memory allocated by the object is a simple <code>delete data</code>. Therefore, our
standard <code>destroy()</code> function was not used.
    </ul>
    Now, the implementation of the members are:
        <pre>
    #include "intarray.ih"

    IntArray::IntArray(unsigned size)
    :
        d_size(size)
    {
        if (d_size &lt; 1)
        {
            cerr &lt;&lt; "IntArray: size of array must be &gt;= 1\n";
            exit(1);
        }
        d_data = new int[d_size];
    }

    IntArray::IntArray(IntArray const &amp;other)
    {
        copy(other);
    }

    IntArray::~IntArray()
    {
        delete[] d_data;
    }

    IntArray const &amp;IntArray::operator=(IntArray const &amp;other)
    {
        if (this != &amp;other)
        {
            delete[] d_data;
            copy(other);
        }
        return *this;
    }

    void IntArray::copy(IntArray const &amp;other)
    {
        d_size = other.d_size;
        d_data = new int[d_size];
        memcpy(d_data, other.d_data, d_size * sizeof(int));
    }

    int &amp;IntArray::operatorIndex(unsigned index) const
    {
        boundary(index);
        return d_data[index];
    }

    int &amp;IntArray::operator[](unsigned index)
    {
        return operatorIndex(index);
    }

    int const &amp;IntArray::operator[](unsigned index) const
    {
        return operatorIndex(index);
    }

    void IntArray::boundary(unsigned index) const
    {
        if (index &gt;= d_size)
        {
            cerr &lt;&lt; "IntArray: boundary overflow, index = " &lt;&lt;
                    index &lt;&lt; ", should range from 0 to " &lt;&lt; d_size - 1 &lt;&lt; endl;
            exit(1);
        }
    }
</pre>
    Especially note the implementation of the <code>operator[]()</code> functions: as
non-const members may call const member functions, and as the implementation
of the <code>const</code> member function is identical to the non-const member
function's implementation, we could implement both <code>operator[]</code> members
inline using an auxiliary function <code>int &amp;operatorIndex(size_t index)
const</code>. It is interesting to note that a <code>const</code> member function may return
a non-const reference (or pointer) return value, referring to one of the data
members of its object. This is a potentially dangerous backdoor breaking data
hiding. However, as the members in the public interface prevents this breach,
we feel confident in defining <code>int &amp;operatorIndex() const</code> as a private
function, knowing that it won't be used for this unwanted purpose.
<p>
<a name="EXTRACTORS"></a><a name="l145"></a>
<h2>9.2: Overloading the insertion and extraction operators</h2>
<a name="overloading/insertextract"></a>    This section describes how a class can be adapted in such a way that it
can be used with the <strong>C++</strong> streams <a name="an1178"></a>
<code>cout</code> and <a name="an1179"></a>
<code>cerr</code> and the
    <a name="an1180"></a>
insertion operator (<<). Adapting a class in such a way that the
<a name="an1181"></a>
<code>istream</code>'s <a name="an1182"></a>
extraction operator (>>) can be used, is implemented
similarly and is simply shown in an example.
<p>
The implementation of an overloaded <code>operator&lt;&lt;()</code> in the context of
<code>cout</code> or <code>cerr</code> involves their class, which is <a name="an1183"></a>
<code>ostream</code>. This class is
declared in the header file <a name="an1184"></a>
<code>ostream</code> and defines only overloaded operator
functions for `basic' types, such as, <code>int</code>, <code>char *</code>, etc.. The purpose
of this section is to show how an <a name="an1185"></a>
insertion operator can be overloaded in
such a way that an object of any class, say <code>Person</code> (see chapter
<a href="cplusplus07.html#MEMORY">7</a>), can be inserted into an <code>ostream</code>. Having made available such
an overloaded operator, the following will be possible:
        <pre>
    Person kr("Kernighan and Ritchie", "unknown", "unknown");

    cout &lt;&lt; "Name, address and phone number of Person kr:\n" &lt;&lt; kr &lt;&lt; endl;
</pre>
    The statement <code>cout</code> << <code>kr</code> involves <code>operator</code><<<code>()</code>.
This member function has two operands: an <code>ostream &amp;</code> and a <code>Person
&amp;</code>. The proposed action is defined in an <a name="an1186"></a>
overloaded global operator
<code>operator</code><<<code>()</code> expecting two arguments:
        <pre>
                                // assume declared in `person.h'
    ostream &amp;operator&lt;&lt;(ostream &amp;, Person const &amp;);

                                // define in some source file
    ostream &amp;operator&lt;&lt;(ostream &amp;stream, Person const &amp;pers)
    {
        return
            stream &lt;&lt;
                "Name:    " &lt;&lt; pers.name() &lt;&lt;
                "Address: " &lt;&lt; pers.address() &lt;&lt;
                "Phone:   " &lt;&lt; pers.phone();
    }
</pre>
    Note the following characteristics of <code>operator</code><<<code>()</code>:
    <ul>
    <li> The function returns a reference to an <code>ostream</code> object,
to enable `chaining' of the insertion operator.
    <li> The two operands of <code>operator</code><<<code>()</code> act as arguments of the
the overloaded function. In the earlier example, the parameter <code>stream</code> is
initialized by <code>cout</code>, the parameter <code>pers</code> is initialized by <code>kr</code>.
    </ul>
<p>
In order to overload the extraction operator for, e.g., the <code>Person</code>
class, members are needed to modify the private data members. Such
<a name="an1187"></a>
<em>modifiers</em> are normally included in the class interface. For the
<code>Person</code> class, the following members should be added to the class
interface:
        <pre>
    void setName(char const *name);
    void setAddress(char const *address);
    void setPhone(char const *phone);
</pre>
    The implementation of these members could be straightforward: the memory
pointed to by the corresponding data member must be deleted, and the data
member should point to a copy of the text pointed to by the parameter. E.g.,
        <pre>
    void Person::setAddress(char const *address)
    {
        delete d_address;
        d_address = strdupnew(address);
    }
</pre>
    A more elaborate function could also check the reasonableness of the new
address. This elaboration, however, is not further pursued here. Instead,
let's have a look at the final <a name="an1188"></a>
overloaded extraction operator
(>>). A simple implementation is:
        <pre>
    istream &amp;operator&gt;&gt;(istream &amp;str, Person &amp;p)
    {
        string name;
        string address;
        string phone;

        if (str &gt;&gt; name &gt;&gt; address &gt;&gt; phone)    // extract three strings
        {
            p.setName(name.c_str());
            p.setAddress(address.c_str());
            p.setPhon(phone.c_str());
        }
        return str;
    }
</pre>
    Note the stepwise approach that is followed with the extraction operator:
first the required information is extracted, using available extraction
operators (like a <code>string</code>-extraction), then, if that succeeds,
<em>modifier</em> members are used to modify the data members of the object to be
extracted. Finally, the stream object itself is returned as a reference.
<p>
<a name="ConversionOperators"></a><a name="l146"></a>
<h2>9.3: Conversion operators</h2>
<a name="overloading/conversion"></a>    A class may be constructed around a basic type. E.g., the class <a name="an1189"></a>
<code>String</code>
was constructed around the <a name="an1190"></a>
<code>char *</code> type. Such a class may define
all kinds of operations, like assignments. Take a look at the following class
interface, designed after the <code>string</code> class:
        <pre>
    class String
    {
        char *d_string;

        public:
            String();
            String(char const *arg);
            ~String();
            String(String const &amp;other);
            String const &amp;operator=(String const &amp;rvalue);
            String const &amp;operator=(char const *rvalue);
    };
</pre>
    Objects from this class can be initialized from a <code>char const *</code>, and
also from a <code>String</code> itself. There is an overloaded assignment operator,
allowing the assignment from a <code>String</code> object and from a <code>char const
*</code>&nbsp;(Note that the assingment from a <code>char const *</code> also includes the
null-pointer. An assignment like <code>stringObject = 0</code> is perfectly in order.).
<p>
Usually, in classes that are less directly coupled to their data than this
<code>String</code> class, there will be an <a name="an1191"></a>
<em>accessor member function</em>, like <code>char
const *String::c_str() const</code>. However, the need to use this latter member
doesn't appeal to our intuition when an array of <code>String</code> objects is defined
by, e.g., a class <code>StringArray</code>. If this latter class provides the
<a name="an1192"></a>
<code>operator[]</code> to access individual <code>String</code> members, we would have the
following interface for <code>StringArray</code>:
        <pre>
    class StringArray
    {
        String *d_store;
        size_t d_n;

        public:
            StringArray(size_t size);
            StringArray(StringArray const &amp;other);
            StringArray const &amp;operator=(StringArray const &amp;rvalue);
            ~StringArray();

            String &amp;operator[](size_t index);
    };
</pre>
    Using the <code>StringArray::operator[]</code>, assignments between the
<code>String</code> elements can simply be realized:
        <pre>
    StringArray sa(10);

    sa[4] = sa[3];  // String to String assignment
</pre>
    It is also possible to assign a <code>char const *</code> to an element of <code>sa</code>:
        <pre>
        sa[3] = "hello world";
</pre>
    Here, the following steps are taken:
    <ul>
    <li> First, <code>sa[3]</code> is evaluated. This results in a <code>String</code> reference.
    <li> Next, the <code>String</code> class is inspected for an overloaded assignment,
        expecting a <code>char const *</code> to its right-hand side. This operator is
        found, and the string object <code>sa[3]</code> can receive its new value.
    </ul>
    Now we try to do it the other way around: how to <em>access</em> the
<code>char const *</code> that's stored in <code>sa[3]</code>? We try the following code:
        <pre>
    char const
        *cp = sa[3];
</pre>
    This, however, won't work: we would need an overloaded assignment operator
for the 'class <code>char const *</code>'. Unfortunately, there isn't such a class, and
therefore we can't build that overloaded assignment operator (see also section
<a href="cplusplus09.html#OverloadableOperators">9.11</a>). Furthermore, <em>casting</em> won't work: the compiler
doesn't know how to <a name="an1193"></a>
cast a <code>String</code> to a <code>char const *</code>.  How to
proceed from here?
<p>
The naive solution is to resort to the accessor member function
<code>c_str()</code>:
        <pre>
        cp = sa[3].c_str()
</pre>
    That solution would work, but it looks so clumsy.... A far better approach
would be to use a <a name="an1194"></a>
<em>conversion operator</em>.
<p>
A <a name="an1195"></a>
<em>conversion operator</em> is a kind of overloaded operator, but this time
the overloading is used to cast the object to another type. Using a conversion
operator a <code>String</code> object may be interpreted as a <code>char const *</code>, which
can then be assigned to another <code>char const *</code>. Conversion operators can be
implemented for all types for which a conversion is needed.
<p>
In the current example, the class <code>String</code> would need a conversion
operator for a <code>char const *</code>. In class interfaces, the general form of a
conversion operator is:
        <pre>
        operator &lt;type&gt;();
</pre>
    In our <code>String</code> class, this would become:
        <pre>
        operator char const *();
</pre>
    The implementation of the conversion operator is straightforward:
        <pre>
    String::operator char const *()
    {
        return d_string;
    }
</pre>
    Notes:
    <ul>
    <li> There is <em>no</em> mentioning of a return type. The conversion operator
returns a value of the type mentioned after the <code>operator</code> keyword.
    <li> In certain situations the compiler needs a hand to <a name="an1196"></a>
disambiguate
our intentions. In a statement like
            <pre>
        cout.form("%s", sa[3])
</pre>
    the compiler is confused: are we going to pass a <code>String &amp;</code> or a
<code>char const *</code> to the <code>form()</code> member function? To help the compiler,
we supply an <a name="an1197"></a>
static_cast:
            <pre>
        cout.form("%s", static_cast&lt;char const *&gt;(sa[3]));
</pre>
    </ul>
<p>
One might wonder what will happen if an object for which, e.g., a
<code>string</code> conversion operator
    <a name="an1198"></a>

    <a name="an1199"></a>
 is defined is inserted into,
e.g., an <code>ostream</code> object, into which <code>string</code> objects can be inserted. In
this case, the compiler will not look for appropriate conversion operators
(like <code>operator string()</code>), but will report an error. For example, the
following example produces a compilation error:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    using namespace std;

    class NoInsertion
    {
        public:
            operator string() const;
    };

    int main()
    {
        NoInsertion object;

        cout &lt;&lt; object &lt;&lt; endl;
    }
</pre>
    The problem is caused by the fact that the compiler notices an insertion,
applied to an object. It will now look for an appropriate overloaded version
of the insertion operator. As it can't find one, it reports a compilation
error, instead of performing a two-stage insertion: first using the <code>operator
string()</code> insertion, followed by the insertion of that <code>string</code> into the
<code>ostream</code> object.
<p>
Conversion operators are used when the compiler is given no choice: an
assignment of a <code>NoInsertion</code> object to a <code>string</code> object is such a
situation. The problem of how to insert an object into, e.g., an <code>ostream</code>
is simply solved: by defining an appropriate overloaded insertion operator,
rather than by resorting to a conversion operator.
<p>
Several considerations apply to conversion operators:
    <ul>
    <li> In general, a class should have at most one conversion operator. When
multiple conversion operators are defined, ambiguities are quickly
introduced.
    <li> A conversion operator should be a `natural extension' of the
facilities of the object. For example, the stream classes define <code>operator
bool()</code>, allowing constructions like <code>if (cin)</code>.
    <li> A conversion operator should return a rvalue. It should do so not
only to enforce data-hiding, but also because implementing a conversion
operator as an lvalue simply won't work. The following little program is a
case in point: the compiler will not perform a two-step conversion and will
therefore try (in vain) to find <code>operator=(int)</code>:
        <pre>
    #include &lt;iostream&gt;

    class Lvalue
    {
        int d_value;

        public:
            operator int&amp;();
    };

        inline Lvalue::operator int&amp;()
        {
            return d_value;
        }

    int main()
    {
        Lvalue lvalue;

        lvalue = 5;     // won't compile: no lvalue::operator=(int)
    };
</pre>
    <li> Conversion operators should be defined as <code>const</code> member functions
if they don't modify their object's data members.
    <li> Conversion operators returning composed objects should return const
references to these objects, rather than the plain object types. Plain object
types would force the compiler to call the composed object's copy constructor,
instead of a reference to the object itself. For example, in the following
program <code>std::string</code>'s copy constructor is not called. It would have been
called if the conversion operator had been declared as <code>operator string()</code>:
        <pre>
    #include &lt;string&gt;

    class XString
    {
        std::string d_s;

        public:
            operator std::string const &amp;() const;
    };

    inline XString::operator std::string const &amp;() const
    {
        return d_s;
    }

    int main()
    {
        XString x;
        std::string s;

        s = x;
    };
</pre>
    </ul>
<p>
<a name="EXPLICIT"></a><a name="l147"></a>
<h2>9.4: The keyword `explicit'</h2>
<a name="overloading/explicit.yo"></a>    Conversions are performed not only by conversion operators, but also by
<a name="an1200"></a>
constructors having one parameter (or multiple parameters, having
    <a name="an1201"></a>
default argument values beyond the first parameter).
<p>
Consider the class <code>Person</code> introduced in chapter <a href="cplusplus07.html#MEMORY">7</a>. This
class has a constructor
        <pre>
        Person(char const *name, char const *address, char const *phone)
</pre>
    This constructor could be given default argument values:
        <pre>
    Person(char const *name, char const *address = "&lt;unknown&gt;",
                             char const *phone = "&lt;unknown&gt;");
</pre>
    In several situations this constructor might be used intentionally,
possibly providing the default <code>&lt;unknown&gt;</code> texts for the address and phone
numbers. For example:
        <pre>
    Person frank("Frank", "Room 113", "050 363 9281");
</pre>
    Also, functions might use <code>Person</code> objects as parameters, e.g., the
following member in a fictitious class <code>PersonData</code> could be available:
        <pre>
    PersonData &amp;PersonData::operator+=(Person const &amp;person);
</pre>
    Now, combining the above two pieces of code, we might, do something like
        <pre>
    PersonData dbase;

    dbase += frank;     // add frank to the database
</pre>
    So far, so good. However, since the <code>Person</code> constructor can also be
used as a conversion operator, it is <em>also</em> possible to do:
        <pre>
    dbase += "karel";
</pre>
    Here, the <code>char const *</code> text `<code>karel</code>' is converted to an (anonymous)
<code>Person</code> object using the abovementioned <code>Person</code> constructor: the second
and third parameters use their <a name="an1202"></a>
default values. Here, an
    <a name="an1203"></a>
<em>implicit conversion</em> is performed from a <code>char const *</code> to a
<code>Person</code> object, which might not be what the programmer had in mind when the
class <code>Person</code> was constructed.
<p>
As another example, consider the situation where a class representing a
container is constructed. Let's assume that the initial construction of
objects of this class is rather complex and time-consuming, but <em>expanding</em>
an object so that it can accomodate more elements is even more
time-consuming. Such a situation might arise when a hash-table is initially
constructed to contain <code>n</code> elements: that's ok as long as the table is not
full, but when the table must be expanded, all its elements normally must be
rehashed to allow for the new table size.
<p>
Such a class could (partially) be defined as follows:
        <pre>
    class HashTable
    {
        size_t d_maxsize;

        public:
            HashTable(size_t n);  // n: initial table size
            size_t size();        // returns current # of elements

                                    // add new key and value
            void add(std::string const &amp;key, std::string const &amp;value);
    };
</pre>
    Now consider the following implementation of <code>add()</code>:
        <pre>
    void HashTable::add(string const &amp;key, string const &amp;value)
    {
        if (size() &gt; d_maxsize * 0.75)  // table gets rather full
            *this = size() * 2;         // Oops: not what we want!

        // etc.
    }
</pre>
    In the first line of the body of <code>add()</code> the programmer first determines
how full the hashtable currently is: if it's more than three quarter full,
then the intention is to double the size of the hashtable. Although this
succeeds, the hashtable will completely fail to fulfill its purpose:
accidentally the programmer assigns an size_t value, intending to tell the
hashtable what its new size should be. This results in the following unwelcome
surprise:
    <ul>
    <li> The compiler notices that no <code>operator=(size_t newsize)</code> is
available for <code>HashTable</code>.
    <li> There is, however, a constructor accepting an size_t, <em>and</em> the
default overloaded assignment operator is still available, expecting a
<code>HashTable</code> as its right-hand operand.
    <li> Thus, the rvalue of the assignment (a <code>HashTable</code>) is obtained by
(implicitly) constructing an (empty) <code>HashTable</code> that can accomodate
<code>size() * 2</code> elements.
    <li> The just constructed empty <code>HashTable</code> is thereupon assigned to the
current <code>HashTable</code>, thus <em>removing all hitherto stored elements from the
current <code>HashTable</code></em>.
    </ul>
    If an <a name="an1204"></a>
 implicit use of a constructor is not
appropriate (or dangerous), it can be prevented using the <a name="an1205"></a>
<code>explicit</code>
modifier with the constructor. Constructors using the <code>explicit</code> modifier
can only be used for the <a name="an1206"></a>
explicit construction of objects, and cannot be
used as implicit type convertors anymore. For example, to prevent the implicit
conversion from <code>size_t</code> to <code>HashTable</code> the class interface of the
class <code>HashTable</code> should declare the constructor
        <pre>
    explicit HashTable(size_t n);
</pre>
    Now the compiler will catch the error in the compilation of
<code>HashTable::add()</code>, producing an error message like
        <pre>
    error: no match for 'operator=' in
                '*this = (this-&gt;HashTable::size()() * 2)'
</pre>
<p>
<a name="OVERLOADINCR"></a><a name="l148"></a>
<h2>9.5: Overloading the increment and decrement operators</h2>
<a name="overloading/increment.yo"></a>Overloading the <a name="an1207"></a>
increment operator (<a name="an1208"></a>
<code>operator++()</code>) and
    <a name="an1209"></a>
decrement operator (<a name="an1210"></a>
<code>operator</code>--<code>()</code>) creates a little problem: there
are two version of each operator, as they may be used as <a name="an1211"></a>
<em>postfix operator</em>
(e.g., <code>x++</code>) or as <a name="an1212"></a>
<em>prefix operator</em> (e.g., <code>++x</code>).
<p>
Used as <em>postfix</em> operator, the value's object is returned as
<a name="an1213"></a>
<em>rvalue</em>, which is an expression having a fixed value: the
post-incremented variable itself disappears from view. Used as <em>prefix</em>
operator, the variable is incremented, and its value is returned as
<a name="an1214"></a>
<em>lvalue</em>, so it can be altered immediately again. Whereas these
characteristics are not <em>required</em> when the operator is overloaded, it is
strongly advised to implement these characteristics in any overloaded
increment or decrement operator.
<p>
Suppose we define a <a name="an1215"></a>
<em>wrapper class</em> around the <code>size_t</code> value
type. The class could have the following (partially shown) interface:
        <pre>
    class Unsigned
    {
        size_t d_value;

        public:
            Unsigned();
            Unsigned(size_t init);
            Unsigned &amp;operator++();
    }
</pre>
    This defines the <em>prefix</em> overloaded increment operator. An <em>lvalue</em>
is returned, as we can deduce from the return type, which is <code>Unsigned &amp;</code>.
<p>
The <em>implementation</em> of the above function could be:
        <pre>
    Unsigned &amp;Unsigned::operator++()
    {
        ++d_value;
        return *this;
    }
</pre>
    In order to define the <em>postfix</em> operator, an overloaded version of the
operator is defined, expecting an <code>int</code> argument. This might be considered a
<a name="an1216"></a>
<em>kludge</em>, or an acceptable application of function overloading. Whatever
your opinion in this matter, the following can be concluded:
    <ul>
    <li> Overloaded increment and decrement operators <em>without parameters</em>
are <em>prefix</em> operators, and should return <em>references</em> to the current
object.
    <li> Overloaded increment and decrement operators <em>having an int
parameter</em> are <em>postfix</em> operators, and should return the value the object
has at the point the overloaded operator is called as a constant value.
    </ul>
    To add the postfix increment operator to the <code>Unsigned</code> wrapper class,
add the following line to the class interface:
        <pre>
    Unsigned const operator++(int);
</pre>
    The <em>implementation</em> of the postfix increment operator should be like
this:
        <pre>
    Unsigned const Unsigned::operator++(int)
    {
        return d_value++;
    }
</pre>
    The simplicity of this implementation is <em>deceiving</em>. Note that:
    <ul>
        <li><code>d_value</code> is used with a postfix increment in the <a name="an1217"></a>
<code>return</code>
expression. Therefore, the value of the <code>return</code> expression is <code>d_value</code>'s
value, before it is incremented; which is correct.
        <li> The return value of the function is an <code>Unsigned</code> value. This
<a name="an1218"></a>
<em>anonymous object</em> is implicitly initialized by the value of <code>d_value</code>, so
there is a <a name="an1219"></a>
hidden constructor call here.
        <li> Anonymous objects are always <a name="an1220"></a>
const objects, so, indeed, the
return value of the postfix increment operator is an <em>rvalue</em>.
        <li> The parameter is not used. It is only part of the implementation
to <em>disambiguate</em> the prefix- and postfix operators in implementations
and declarations.
    </ul>
    When the object has a more complex data organization, using a
    <a name="an1221"></a>
copy constructor might be preferred. For instance, assume we want to
implement the postfix increment operator in the class <code>PersonData</code>,
mentioned in section <a href="cplusplus09.html#EXPLICIT">9.4</a>. Presumably, the <code>PersonData</code> class
contains a complex inner <a name="an1222"></a>
data organization. If the <code>PersonData</code> class
would maintain a pointer <code>Person *current</code> to the <code>Person</code> object that is
currently selected, then the postfix increment operator for the class
<code>PersonData</code> could be implemented as follows:
        <pre>
    PersonData PersonData::operator++(int)
    {
        PersonData tmp(*this);

        incrementCurrent();     // increment `current', somehow.
        return tmp;
    }
</pre>
    A matter of concern here could be that this operation actually requires
<em>two</em> calls to the copy constructor: first to keep the current state, then
to copy the <code>tmp</code> object to the (anonymous) return value. In some cases this
double call of the <a name="an1223"></a>
 copy constructor might be
avoidable, by defining a specialized constructor. E.g.,
        <pre>
    PersonData PersonData::operator++(int)
    {
        return PersonData(*this, incrementCurrent());
    }
</pre>
    Here, <code>incrementCurrent()</code> is supposed to return the information which
allows the constructor to set its <code>current</code> data member to the pre-increment
value, at the same time incrementing <code>current</code> of the actual
<code>PersonData</code> object. The above constructor would have to:
    <ul>
    <li> initialize its data members by copying the values of the data members
of the <code>this</code> object.
    <li> reassign <code>current</code> based on the return value of its second
parameter, which could be, e.g., an index.
    </ul>
    At the same time, <code>incrementCurrent()</code> would have incremented
<code>current</code> of the actual <code>PersonData</code> object.
<p>
The general rule is that double calls of the copy constructor can be
avoided if a <a name="an1224"></a>
specialized constructor can be defined initializing an
object to the pre-increment state of the current object. The current object
itself has its necessary data members incremented by a function, whose
return value is passed as argument to the constructor, thereby informing the
constructor of the pre-incremented state of the involved data members. The
postfix increment operator will then return the thus constructed (anonymous)
object, and no copy constructor is ever called.
<p>
Finally it is noted that the call of the increment or decrement operator
using  <a name="an1225"></a>
 its overloaded
function name might require us to provide an (any) <code>int</code> argument to inform
the compiler that we want the postfix increment function. E.g.,
        <pre>
    PersonData p;

    p = other.operator++();     // incrementing `other', then assigning `p'
    p = other.operator++(0);    // assigning `p', then incrementing `other'
</pre>
<p>
<a name="OVERLOADBINARY"></a><a name="l149"></a>
<h2>9.6: Overloading binary operators</h2>
<a name="overloading/binary.yo"></a>    In various classes overloading binary operators (like <a name="an1226"></a>
<code>operator+()</code>) can
be a very natural extension of the class's functionality. For example, the
<code>std::string</code> class has various overloaded forms of <code>operator+()</code> as have
most <em>abstract containers</em>, covered in chapter <a href="cplusplus12.html#Containers">12</a>.
<p>
Most binary operators come in two flavors: the plain binary operator (like
the <code>+</code> operator) and the arithmetic assignment variant (like the <code>+=</code>
operator). Whereas the plain binary operators return const expression values,
the arithmetic assignment operators return a (non-const) reference to the
object to which the operator was applied. For example, with
<code>std::string</code> objects the following code (annotated below the example)
may be used:
        <pre>
    std::string s1;
    std::string s2;
    std::string s3;

    s1 = s2 += s3;                  // 1
    (s2 += s3) + " postfix";        // 2
    s1 = "prefix " + s3;            // 3
    "prefix " + s3 + "postfix";     // 4
    ("prefix " + s3) += "postfix";  // 5
</pre>
    <ul>
    <li> at <code>// 1</code> the contents of <code>s3</code> is added to <code>s2</code>. Next, <code>s2</code>
is returned, and its new contents are assigned to <code>s1</code>. Note that <code>+=</code>
returns <code>s2</code> itself.
    <li> at <code>// 2</code> the contents of <code>s3</code> is also added to <code>s2</code>, but as
<code>+=</code> returns <code>s2</code> itself, it's possible to add some more to <code>s2</code>
    <li> at <code>// 3</code> the <code>+</code> operator returns a <code>std::string</code> containing
the concatenation of the text <code>prefix</code> and the contents of <code>s3</code>. This
string returned by the <code>+</code> operator is thereupon assigned to <code>s1</code>.
    <li> at <code>// 4</code> the <code>+</code> operator is applied twice. The effect is:
        <ol>
        <li> The first <code>+</code> returns a <code>std::string</code> containing
the concatenation of the text <code>prefix</code> and the contents of <code>s3</code>.
        <li> The second <code>+</code> operator takes this returned string as its left
hand value, and returns a string containing the concatenated text of its left
and right hand operands.
        <li> The string returned by the second <code>+</code> operator represents the
value of the expression.
        </ol>
    <li> statement <code>// 5</code> should not compile (although it does compile with
the <a name="an1227"></a>
<code>Gnu</code> compiler version 3.1.1). It should not compile, as the <code>+</code>
operator should return a <code>const</code> string, thereby preventing its modification
by the subsequent <code>+=</code> operator. Below we will consequently follow this line
of reasoning, and will ensure that overloaded binary operators will always
return <code>const</code> values.
    </ul>
<p>
Now consider the following code, in which a class <code>Binary</code> supports
an overloaded <code>operator+()</code>:
        <pre>
    class Binary
    {
        public:
            Binary();
            Binary(int value);
            Binary const operator+(Binary const &amp;rvalue);
    };

    int main()
    {
        Binary b1;
        Binary b2(5);

        b1 = b2 + 3;            // 1
        b1 = 3 + b2;            // 2
    }
</pre>
    Compilation of this little program fails for statement <code>// 2</code>, with the
compiler reporting an error like:
        <pre>
    error: no match for 'operator+' in '3 + b2'
</pre>
    Why is statement <code>// 1</code> compiled correctly whereas statement <code>// 2</code>
won't compile?
<p>
In order to understand this, the notion of a <a name="an1228"></a>
<em>promotion</em> is
introduced. As we have seen in section <a href="cplusplus09.html#EXPLICIT">9.4</a>, constructors requiring
a single argument may be implicitly activated when an object is apparently
initialized by an argument of a corresponding type. We've encountered this
repeatedly with <code>std::string</code> objects, when an <code>ASCII-Z</code> string was used
to initialize a <code>std::string</code> object.
<p>
In situations where a member function expects a <code>const &amp;</code> to an object
of its own class (like the <code>Binary const &amp;</code> that was specified in the
declaration of the <code>Binary::operator+()</code> member mentioned above), the type
of the actually used argument may also be any type that can be used as an
argument for a single-argument constructor of that class. This implicit call
of a constructor to obtain an object of the proper type is called a
<em>promotion</em>.
<p>
So, in statement <code>// 1</code>, the <code>+</code> operator is called for the <code>b2</code>
object. This operator expects another <code>Binary</code> object as its right hand
operand. However, an <code>int</code> is provided. As a constructor <code>Binary(int)</code>
exists, the <code>int</code> value is first promoted to a <code>Binary</code> object. Next, this
<code>Binary</code> object is passed as argument to the <code>operator+()</code> member.
<p>
Note that no promotions are possibly in statement <code>// 2</code>: here the <code>+</code>
operator is applied to an <code>int</code> typed value, which has no concept of a
`constructor', `member function' or `promotion'.
<p>
How, then, are promotions of left-hand operands realized in statements
like <code>"prefix " + s3</code>? Since promotions are applied to function arguments,
we must make sure that both operands of binary operators are arguments. This
means that binary operators are declared as <a name="an1229"></a>
<em>classless functions</em>, also
called <a name="an1230"></a>
<em>free functions</em>. However, they conceptually belong to the class for
which they implement the binary operator, and so they should be declared in
the class's header file. We will cover their implementations shortly, but here
is our first revision of the declaration of the class <code>Binary</code>, declaring an
overloaded <code>+</code> operator as a free function:
        <pre>
    class Binary
    {
        public:
            Binary();
            Binary(int value);
    };

    Binary const operator+(Binary const &amp;l_hand, Binary const &amp;r_hand);
</pre>
<p>
By defining binary operators as free functions, the following promotions
are possible:
    <ul>
    <li> If the left-hand operand is of the intended class type, the right
hand argument will be promoted whenever possible
    <li> If the right-hand operand is of the intended class type, the left
hand argument will be promoted whenever possible
    <li> No promotions occur when none of the operands are of the intended
class type
    <li> An ambiguity occurs when promotions to different classes are possible
for the two operands. For example:
        <pre>
    class A;

    class B
    {
        public:
            B(A const &amp;a);
    };

    class A
    {
        public:
            A();
            A(B const &amp;b);
    };

    A const operator+(A const &amp;a, B const &amp;b);
    B const operator+(B const &amp;b, A const &amp;a);

    int main()
    {
        A a;

        a + a;
    };
</pre>
    Here, both overloaded <code>+</code> operators are possible when compiling
the statement <code>a + a</code>. The ambiguity must be solved by explicitly promoting
one of the arguments, e.g., <code>a + B(a)</code> will allow the compiler to resolve
the ambiguity to the first overloaded <code>+</code> operator.
    </ul>
<p>
The next step is to implement the corresponding
overloaded arithmetic assignment operator. As this operator <em>always</em> has a
left-hand operand which is an object of its own class, it is implemented as a
true member function. Furthermore, the arithmetic assignment operator should
return a reference to the object to which the arithmetic operation applies, as
the object might be modified in the same statement. E.g.,
    <code>(s2 += s3) + " postfix"</code>. Here is our second revision of the class
<code>Binary</code>, showing both the declaration of the plain binary operator and the
corresponding arithmetic assignment operator:
        <pre>
    class Binary
    {
        public:
            Binary();
            Binary(int value);
            Binary const operator+(Binary const &amp;rvalue);

            Binary &amp;operator+=(Binary const &amp;other);
    };

    Binary const operator+(Binary const &amp;l_hand, Binary const &amp;r_hand);
</pre>
<p>
Finally, having available the arithmetic assignment operator, the
implementation of the plain binary operator turns out to be extremely
simple. It contains of a single return statement, in which an anonymous object
is constructed to which the arithmetic assignment operator is applied. This
anonymous object is then returned by the plain binary operator as its
<code>const</code> return value. Since its implementation consists of merely one
statement it is usually provided in-line, adding to its efficiency:
        <pre>
    class Binary
    {
        public:
            Binary();
            Binary(int value);
            Binary const operator+(Binary const &amp;rvalue);

            Binary &amp;operator+=(Binary const &amp;other);
    };

    Binary const operator+(Binary const &amp;l_hand, Binary const &amp;r_hand)
    {
        return Binary(l_hand) += r_hand;
    }
</pre>
    One might wonder where the temporary value is located. Most compilers
apply in these cases a procedure called `<a name="an1231"></a>
<em>return value optimization</em>': the
anonymous object is created at the location where the eventual returned object
will be stored. So, rather than first creating a separate temporary object,
and then copying this object later on to the return value, it initializes the
return value using the <code>l_hand</code> argument, and then applies the <code>+=</code>
operator to add the <code>r_hand</code> argument to it. Without return value
optimization it would have to:
    <ul>
    <li> create separate room to accomodate the return value
    <li> initialize a temporary object using <code>l_hand</code>
    <li> Add <code>r_hand</code> to it
    <li> Use the copy constructor to copy the temporary object to the return
        value.
    </ul>
    Return value optimization is not required, but optionally available to
compilers. As it has no negative side effects, most compiler use it.
<p>
<a name="l150"></a>
<h2>9.7: Overloading `operator new(size_t)'</h2>
<a name="overloading/new"></a>When <a name="an1232"></a>
<code>operator new</code> is overloaded, it must have a <a name="an1233"></a>
<code>void *</code> return type,
and at least an argument of type <a name="an1234"></a>
<code>size_t</code>. The <code>size_t</code> type is defined in
the header file <a name="an1235"></a>
<code>cstddef</code>, which must therefore be included when the
operator <a name="an1236"></a>
<code>new</code> is overloaded.
<p>
It is also possible to define multiple versions of the <code>operator new</code>, as
long as each version has its own unique set of arguments. The global <code>new</code>
operator can still be used, through the <a name="an1237"></a>
<code>::</code>-operator. If a class <code>X</code>
overloads the operator <code>new</code>, then the system-provided operator <code>new</code> is
activated by
                        <pre>
        X *x = ::new X();
</pre>
    Overloading <a name="an1238"></a>
<code>new[]</code> is discussed in section <a href="cplusplus09.html#NEWDELETEARRAY">9.9</a>.
The following example shows an overloaded version of <code>operator new</code>:
        <pre>
    #include &lt;cstddef&gt;

    void *X::operator new(size_t sizeofX)
    {
        void *p = new char[sizeofX];

        return memset(p, 0, sizeof(X));
    }
</pre>
    Now, let's see what happens when <code>operator new</code> is overloaded for the
<code>class X</code>. Assume that class is defined as
    follows&nbsp;(For the sake of simplicity we have violated the principle
of <a name="an1239"></a>
encapsulation here. The principle of encapsulation, however, is
immaterial to the discussion of the workings of the operator <code>new</code>.):
        <pre>
    class X
    {
        public:
            void *operator new(size_t sizeofX);

            int d_x;
            int d_y;
    };
</pre>
    Now, consider the following program fragment:
        <pre>
    #include "x.h"  // class X interface
    #include &lt;iostream&gt;
    using namespace std;

    int main()
    {
        X *x = new X();

        cout &lt;&lt; x-&gt;d_x &lt;&lt; ", " &lt;&lt; x-&gt;d_y &lt;&lt; endl;
    }
</pre>
This small program produces the following output:
        <pre>
        0, 0
</pre>
    At the call of <code>new X()</code>, our little program performed the following
actions:
    <ul>
    <li> First, <code>operator new</code> was called, which allocated and initialized
        a block of memory, the size of an <code>X</code> object.
    <li> Next, a pointer to this block of memory was passed to the
        (default) <code>X()</code> constructor. Since no constructor was defined,
        the constructor itself didn't do anything at all.
    </ul>
    Due to the initialization of the block of memory by <code>operator new</code>
the allocated <code>X</code> object was already initialized to zeros when the
constructor was called.
<p>
Non-static member functions are passed a (hidden) pointer to the object on
which they should operate. This <a name="an1240"></a>
hidden pointer becomes the <a name="an1241"></a>
<code>this</code> pointer
in <a name="an1242"></a>
non-static member functions. This procedure is also followed for
constructors.  In the next pieces of pseudo <strong>C++</strong> code, the pointer is made
visible. In the first part an <code>X</code> object <code>x</code> is defined directly, in the
second part of the example the (overloaded) <code>operator new</code> is used:
        <pre>
    X::X(&amp;x);                       // x's address is passed to the
                                    // constructor
    void *ptr = X::operator new();  // new allocates the memory

    X::X(ptr);                      // next the constructor operates on the
                                    // memory returned by 'operator new'
</pre>
    Notice that in the pseudo <code>C++</code> fragment the member functions were
treated as static member function of the class <code>X</code>. Actually, <code>operator
new</code> <em>is</em> a <a name="an1243"></a>
static member function of its class: it cannot reach data
members of its object, since it's normally the task of the <code>operator new</code>
to create room for that object. It can do that by allocating enough
memory, and by initializing the area as required. Next, the memory is passed
(as the <code>this</code> pointer) to the constructor for further processing. The
fact that an overloaded operator <code>new</code> is actually a static function, not
requiring an object of its class, can be illustrated in the following (frowned
upon in normal situations!) program fragment, which can be compiled without
problems (assume <code>class X</code> has been defined and is available as before):
        <pre>
    int main()
    {
        X x;

        X::operator new(sizeof x);
    }
</pre>
The call to <code>X::operator new()</code> returns a <code>void *</code> to an initialized block
of memory, the size of an <code>X</code> object.
<p>
The <code>operator new</code> can have multiple parameters. The first parameter is
initialized by an <a name="an1244"></a>
implicit argument and is always the <a name="an1245"></a>
<code>size_t</code> parameter,
other parameters are initialized by <a name="an1246"></a>
explicit arguments that are specified
when <code>operator new</code> is used. For example:
        <pre>
    class X
    {
        public:
            void *operator new(size_t p1, size_t p2);
            void *operator new(size_t p1, char const *fmt, ...);
    };

    int main()
    {
        X
            *p1 = new(12) X(),
            *p2 = new("%d %d", 12, 13) X(),
            *p3 = new("%d", 12) X();
    }
</pre>
    The pointer <code>p1</code> is a pointer to an <code>X</code> object for which the memory
has been allocated by the call to the first overloaded <code>operator new</code>,
followed by the call of the constructor <code>X()</code> for that block of memory.  The
pointer <code>p2</code> is a pointer to an <code>X</code> object for which the memory has been
allocated by the call to the second overloaded <code>operator new</code>, followed
again by a call of the constructor <code>X()</code> for its block of memory.  Notice
that pointer <code>p3</code> also uses the second overloaded <code>operator new()</code>, as
that <a name="an1247"></a>
overloaded operator accepts a <a name="an1248"></a>
variable number of arguments, the
first of which is a <code>char const *</code>.
<p>
Finally note that no explicit argument is passed for <code>new</code>'s first
parameter, as this argument is implicitly provided by the type specification
that's required for operator <code>new</code>.
<p>
<a name="l151"></a>
<h2>9.8: Overloading `operator delete(void *)'</h2>
<a name="overloading/delete"></a>The <a name="an1249"></a>
<code>delete</code> operator may be overloaded too. The <a name="an1250"></a>
<code>operator delete</code> must
have a <a name="an1251"></a>
<code>void *</code> argument, and an optional second argument of type <a name="an1252"></a>
<code>size_t</code>,
which is the size in bytes of objects of the class for which the <code>operator
delete</code> is overloaded. The return type of the overloaded <code>operator delete</code> is
<code>void</code>.
<p>
Therefore, in a class the operator <code>delete</code> may be overloaded using the
following prototype:
        <pre>
        void operator delete(void *);
</pre>
    or
        <pre>
        void operator delete(void *, size_t);
</pre>
    Overloading <code>delete[]</code> is discussed in section <a href="cplusplus09.html#NEWDELETEARRAY">9.9</a>.
<p>
The `home-made' <code>operator delete</code> is called after executing the
<a name="an1253"></a>
destructor of the associated class. So, the statement
        <pre>
        delete ptr;
</pre>
    with <code>ptr</code> being a pointer to an object of the class <code>X</code> for which the
operator <code>delete</code> was overloaded, boils down to the following statements:
        <pre>
    X::~X(ptr);     // call the destructor function itself

                    // and do things with the memory pointed to by ptr
    X::operator delete(ptr, sizeof(*ptr));
</pre>
    The overloaded <code>operator delete</code> may do whatever it wants to do with the
memory pointed to by <code>ptr</code>. It could, e.g., simply delete it. If that
would be the preferred thing to do, then the
    <a name="an1254"></a>
 default <code>delete</code> operator
can be activated using the <a name="an1255"></a>
<code>::</code> <a name="an1256"></a>
scope resolution operator. For example:
        <pre>
    void X::operator delete(void *ptr)
    {
        // any operation considered necessary, then:
        ::delete ptr;
    }
</pre>
<p>
<a name="NEWDELETEARRAY"></a><a name="l152"></a>
<h2>9.9: Operators `new[]' and `delete[]'</h2>
<a name="overloading/newdeletearray"></a>In sections <a href="cplusplus07.html#NEWARRAY">7.1.1</a>, <a href="cplusplus07.html#DELETEARRAY">7.1.2</a> and <a href="cplusplus07.html#DELETEPTRS">7.2.1</a>
    <a name="an1257"></a>
<code>operator new[]</code> and <a name="an1258"></a>
<code>operator delete[]</code> were introduced.  Like
<a name="an1259"></a>
<code>operator new</code> and <a name="an1260"></a>
<code>operator delete</code> the
operators <code>new[]</code> and <code>delete[]</code> may be overloaded.  Because it is
possible to overload <code>new[]</code> and <code>delete[]</code> as well as <code>operator new</code>
and <code>operator delete</code>, one should be careful in selecting the appropriate
set of operators. The following <a name="an1261"></a>
rule of thumb should be followed:
    <blockquote>If <code>new</code> is used to <a name="an1262"></a>
allocate memory, <code>delete</code> should be used
        to <a name="an1263"></a>
deallocate memory. If <code>new[]</code> is used to allocate memory,
        <code>delete[]</code> should be used to deallocate memory.</blockquote>
<p>
The <a name="an1264"></a>
default way these operators act is as follows:
    <ul>
    <li><code>operator new</code> is used to allocate a single object or
        <a name="an1265"></a>
primitive value. With an object, the object's <a name="an1266"></a>
constructor is
called. <li><code>operator delete</code> is used to return the memory allocated by
<code>operator new</code>. Again, with an object, the <a name="an1267"></a>
destructor of its class is
called. <li><code>operator new[]</code> is used to allocate a series of primitive values
or objects. Note that if a series of objects is allocated, the class's
    <a name="an1268"></a>
default constructor is called to initialize each individual
object. <li><code>operator delete[]</code> is used to delete the memory previously
allocated by <code>new[]</code>. <em>If</em> objects were previously allocated, then the
destructor wil be called for each individual object. However, if
    <a name="an1269"></a>
<em>pointers to objects</em> were allocated, <em>no destructor is called</em>, as a
pointer is considered a primitive type, and certainly not an object.
    </ul>
    Operators <code>new[]</code> and <code>delete[]</code> may only be overloaded in
classes. Consequently, when allocating primitive types or
pointers to objects only the default line of action is followed: when arrays
of pointers to objects are deleted, a <a name="an1270"></a>
memory leak occurs unless the objects
to which the pointers point were deleted earlier.
<p>
In this section the mere syntax for overloading operators
<code>new[]</code> and <code>delete[]</code> is presented. It is left as an
    <a name="an1271"></a>
exercise to the reader to make good use of these overloaded operators.
<p>
<a name="l153"></a>
<h3>9.9.1: Overloading `new[]'</h3>
    <a name="overloading/newarray"></a>    To overload <code>operator new[]</code> in a class <code>Object</code> the interface should
contain the following lines, showing multiple forms of overloaded forms of
<code>operator new[]</code>:
        <pre>
    class Object
    {
        public:
            void *operator new[](size_t size);
            void *operator new[](size_t index, size_t extra);
    };
</pre>
    The first form shows the basic form of <code>operator new[]</code>. It
should return a <a name="an1272"></a>
<code>void *</code>, and defines at least a <a name="an1273"></a>
<code>size_t</code> parameter. When
<code>operator new[]</code> is called, <code>size</code> contains the number of <em>bytes</em> that
must be allocated for the required number of objects. These objects can be
initialized by the <a name="an1274"></a>
<em>global operator new[]</em> using the form <a name="an1275"></a>

        <pre>
    ::new Object[size / sizeof(Object)]
</pre>
    Or, alternatively, the required (uninitialized) amount of memory can be
allocated using:
        <pre>
    ::new char[size]
</pre>
An example of an overloaded operator <code>new[]</code> member function, returning an
array of <code>Object</code> objects all filled with 0-bytes, is:
        <pre>
    void *Object::operator new[](size_t size)
    {
        return memset(new char[size], 0, size);
    }
</pre>
    Having constructed the overloaded operator <code>new[]</code>, it will be used
automatically in statements like:
        <pre>
    Object *op = new Object[12];
</pre>
    Operator <code>new[]</code> may be overloaded using additional parameters. The
second form of the overloaded operator <code>new[]</code> shows such an additional
<code>size_t</code> parameter. The definition of such a function is standard, and
could be:
        <pre>
    void *Object::operator new[](size_t size, size_t extra)
    {
        size_t n = size / sizeof(Object);
        Object *op = ::new Object[n];

        for (size_t idx = 0; idx &lt; n; idx++)
            op[idx].value = extra;          // assume a member `value'

        return op;
    }
</pre>
    To use this overloaded operator, only the additional parameter must be
provided. It is given in a <a name="an1276"></a>
parameter list just after the name of the
operator itself:
        <pre>
    Object
        *op = new(100) Object[12];
</pre>
    This results in an array of 12 <code>Object</code> objects, all having their
<code>value</code> members set to 100.
<p>
<a name="l154"></a>
<h3>9.9.2: Overloading `delete[]'</h3>
    <a name="overloading/deletearray"></a>    Like <code>operator new[]</code> <a name="an1277"></a>
<code>operator delete[]</code> may be overloaded.
To overload <code>operator delete[]</code> in a class <code>Object</code> the interface should
contain the following lines, showing multiple forms of overloaded forms of
<code>operator delete[]</code>:
        <pre>
    class Object
    {
        public:
            void operator delete[](void *p);
            void operator delete[](void *p, size_t index);
            void operator delete[](void *p, int extra, bool yes);
    };
</pre>
<p>
<a name="l155"></a>
<strong>9.9.2.1: `delete[](void *)'</strong>
<p>
The first form shows the basic form of <code>operator delete[]</code>. Its
parameter is initialized to the address of a block of memory previously
allocated by <code>Object::new[]</code>. These objects can be
deleted by the <a name="an1278"></a>
<em>global operator delete[]</em> using the form
<a name="an1279"></a>
<code>::delete[]</code>. However, the compiler expects <code>::delete[]</code> to receive a
pointer to <code>Objects</code>, so a <a name="an1280"></a>
type cast is necessary:
        <pre>
    ::delete[] reinterpret_cast&lt;Object *&gt;(p);
</pre>
    An example of an overloaded operator <code>delete[]</code> is:
        <pre>
    void Object::operator delete[](void *p)
    {
        cout &lt;&lt; "operator delete[] for Objects called\n";
        ::delete[] reinterpret_cast&lt;Object *&gt;(p);
    }
</pre>
    Having constructed the overloaded operator <code>delete[]</code>, it will be used
automatically in statements like:
        <pre>
        delete[] new Object[5];
</pre>
<p>
<a name="l156"></a>
<strong>9.9.2.2: `delete[](void *, size_t)'</strong>
<p>
Operator <code>delete[]</code> may be overloaded using additional
parameters. However, if overloaded as
        <pre>
    void operator delete[](void *p, size_t size);
</pre>
    then <code>size</code> is automatically initialized to the size (in bytes) of the
block of memory to which <code>void *p</code> points. If this form is defined, then the
first form should <em>not</em> be defined, to avoid
    <a name="an1281"></a>
 ambiguity.  An example of this form of
<code>operator delete[]</code> is:
        <pre>
    void Object::operator delete[](void *p, size_t size)
    {
        cout &lt;&lt; "deleting " &lt;&lt; size &lt;&lt; " bytes\n";
        ::delete[] reinterpret_cast&lt;Object *&gt;(p);
    }
</pre>
<p>
<a name="l157"></a>
<strong>9.9.2.3: Alternate forms of overloading operator `delete[]'</strong>
<p>
If additional parameters are defined, as in
        <pre>
    void operator delete[](void *p, int extra, bool yes);
</pre>
    an <a name="an1282"></a>
explicit argument list must be provided. With <code>delete[]</code>, the
argument list is specified <em>following</em> the brackets:
        <pre>
    delete[](new Object[5], 100, false);
</pre>
<p>
<a name="FUNOBJ"></a><a name="l158"></a>
<h2>9.10: Function Objects</h2>
<a name="overloading/functionobject.yo"></a><em>Function Objects</em> are created by overloading the
    <a name="an1283"></a>
<em>function call operator</em> <a name="an1284"></a>
<code>operator()()</code>. By defining the function
call operator an object masquerades as a function, hence the term
    <a name="an1285"></a>
<em>function objects</em>.
<p>
Function objects play an important role in
    <a href="cplusplus17.html#STL"><em>generic algorithms</em></a> and their use is preferred over
alternatives like <a name="an1286"></a>
pointers to functions. The fact that they are
important in the context of <a name="an1287"></a>
generic algorithms constitutes some sort of
a didactical dilemma: at this point it would have been nice if generic
algorithms would have been covered, but for the discussion of the generic
algorithms knowledge of function objects is required. This
    <a name="an1288"></a>
bootstrapping problem is solved in a well known way: by ignoring the
dependency.
<p>
Function objects are objects for which <code>operator()()</code> has been
defined. Function objects are commonly used in combination with generic
algorithms, but also in situations where otherwise pointers to
functions would have been used. Another reason for using function objects is
to support <a name="an1289"></a>
<code>inline</code> functions, which cannot be used in combination with
pointers to functions.
<p>
Assume we have a class <code>Person</code> and an array of <code>Person</code> objects. Further
assume that the array is not sorted. A well known procedure for finding a
particular <code>Person</code> object in the array is to use the function
<a name="an1290"></a>
<code>lsearch()</code>, which performs a <a name="an1291"></a>
<em>lineair search</em> in an array. A program
fragment using this function is:
        <pre>
    Person &amp;target = targetPerson();    // determine the person to find
    Person *pArray;
    size_t n = fillPerson(&amp;pArray);

    cout &lt;&lt; "The target person is";

    if (!lsearch(&amp;target, pArray, &amp;n, sizeof(Person), compareFunction))
        cout &lt;&lt; " not";

    cout &lt;&lt; "found\n";
</pre>
    The function <code>targetPerson()</code> is called to determine the person we're
looking for, and the function <code>fillPerson()</code> is called to fill the array.
Then <code>lsearch()</code> is used to locate the target person.
<p>
The comparison function must be available, as its address is one of the
arguments of the <code>lsearch()</code> function. It could be something like:
        <pre>
    int compareFunction(Person const *p1, Person const *p2)
    {
        return *p1 != *p2;      // lsearch() wants 0 for equal objects
    }
</pre>
    This, of course, assumes that the <a name="an1292"></a>
<code>operator!=()</code> has been overloaded in
the class <code>Person</code>, as it is quite unlikely that a <a name="an1293"></a>
bytewise comparison
will be appropriate here. But overloading <code>operator!=()</code> is no big deal, so
let's assume that that operator is available as well.
<p>
With <code>lsearch()</code> (and friends, having parameters that are
    <a name="an1294"></a>
pointers to functions) an <a name="an1295"></a>
<em>inline</em> compare function cannot be used:
as the address of the <code>compare()</code> function must be known to the
<code>lsearch()</code> function. So, on average <code>n / 2</code> times <em>at least</em> the
following actions take place:
    <ol>
    <li> The two arguments of the compare function are pushed on the stack;
    <li> The value of the final parameter of <code>lsearch()</code> is determined,
producing the address of  <code>compareFunction()</code>;
    <li> The compare function is called;
    <li> Then, inside the compare function the address of the right-hand
argument of the 
        <code>Person::operator!=()</code> argument is pushed on the stack;
    <li> The <code>Person::operator!=()</code> function is evaluated;
    <li> The argument of the <code>Person::operator!=()</code> function is popped off
the stack again;
    <li> The two arguments of the compare function are popped off the stack
again.
    </ol>
    When function objects are used a different picture emerges. Assume we have
constructed a function <code>PersonSearch()</code>, having the following prototype
(realize that this is not the preferred approach. Normally a
<a name="an1296"></a>
generic algorithm will be preferred to a home-made function. But for now
our <code>PersonSearch()</code> function is used to illustrate the use and
implementation of a function object):
        <pre>
    Person const *PersonSearch(Person *base, size_t nmemb,
                               Person const &amp;target);
</pre>
    This function can be used as follows:
        <pre>
    Person &amp;target = targetPerson();
    Person *pArray;
    size_t n = fillPerson(&amp;pArray);

    cout &lt;&lt; "The target person is";

    if (!PersonSearch(pArray, n, target))
        cout &lt;&lt; " not";

    cout &lt;&lt; "found\n";
</pre>
    So far, nothing much has been altered. We've replaced the call to
<code>lsearch()</code> with a call to another function: <code>PersonSearch()</code>.  Now we
show what happens inside <code>PersonSearch()</code>:
        <pre>
    Person const *PersonSearch(Person *base, size_t nmemb,
                                Person const &amp;target)
    {
        for (int idx = 0; idx &lt; nmemb; ++idx)
            if (target(base[idx]))
                return base + idx;
        return 0;
    }
</pre>
    The implementation shows a plain <a name="an1297"></a>
linear search. However, in the
for-loop the expression <code>target(base[idx])</code> shows our <code>target</code> object
used as a function object. Its implementation can be simple:
        <pre>
    bool Person::operator()(Person const &amp;other) const
    {
        return *this != other;
    }
</pre>
    Note the somewhat <a name="an1298"></a>
peculiar syntax: <a name="an1299"></a>
<code>operator()()</code>. The first set
of parentheses define the particular operator that is overloaded: the function
call operator. The second set of parentheses define the parameters that are
required for this function. <code>Operator()()</code> appears in the class header
file as:
        <pre>
    bool operator()(Person const &amp;other) const;
</pre>
    Now, <code>Person::operator()()</code> is a simple function. It contains but one
statement, so we could consider making it <a name="an1300"></a>
inline. Assuming that we do, than
this is what happens when <code>operator()()</code> is called:
    <ul>
    <li> The address of the right-hand argument of the
    <code>Person::operator!=()</code> argument is pushed on the stack,
    <li> The <code>operator!=()</code> function is evaluated,
    <li> The argument of <code>Person::operator!=()</code> argument is popped off the
stack,
    </ul>
    Note that due to the fact that <code>operator()()</code> is an inline function, it
is not actually called. Instead <code>operator!=()</code> is called immediately.  Also
note that the required <a name="an1301"></a>
stack operations are fairly modest.
<p>
So, function objects may be defined inline. This is not possible for
functions that are called indirectly (i.e., using pointers to functions).
Therefore, even if the function object needs to do very little work it has to
be defined as an ordinary function if it is going to be called via
pointers. The overhead of performing the indirect call may annihilate the
advantage of the flexibility of calling functions indirectly. In these cases
function objects that are defined as inline functions can result in an
increase of efficiency of the program.
<p>
Finally, function objects may  access the private data of their objects
directly. In a search algorithm where a compare function is used (as with
<code>lsearch()</code>) the target and array elements are passed to the compare
function using pointers, involving extra stack handling. When function objects
are used, the target person doesn't vary within a single search
task. Therefore, the target person could be passed to the constructor of the
function object doing the comparison. This is in fact what happened in the
expression <code>target(base[idx])</code>, where only one argument is passed to the
<code>operator()()</code> member function of the <code>target</code> function object.
<p>
As noted, function objects play a central role
in generic algorithms.  In chapter <a href="cplusplus17.html#STL">17</a> these generic algorithms are
discussed in detail. Furthermore, in that chapter
    <em>predefined function objects</em> will be introduced, further emphasizing
the importance of the function object concept.
<p>
<a name="MANIPCONSTRUCTION"></a><a name="l159"></a>
<h3>9.10.1: Constructing manipulators</h3>
    <a name="overloading/manipulators"></a>In chapter <a href="cplusplus05.html#IOStreams">5</a> we saw constructions like <code>cout</code> << <code>hex</code>
<< <code>13</code> << <code> endl</code> to display the value 13 in <a name="an1302"></a>
hexadecimal
format. One may wonder by what magic the <a name="an1303"></a>
<code>hex</code> <a name="an1304"></a>
manipulator accomplishes
this. In this section the construction of manipulators like <code>hex</code> is
covered.
<p>
Actually the construction of a manipulator is rather simple. To start, a
definition of the manipulator is needed. Let's assume we want to create a
manipulator <code>w10</code> which will set the <a name="an1305"></a>
field width of the next field to be
written to the <code>ostream</code> object to 10. This manipulator is constructed as a
function. The <code>w10</code> function will have to know about the <code>ostream</code> object
in which the width must be set. By providing the function with a <code>ostream &amp;</code>
parameter, it obtains this knowledge. Now that the function knows about the
<code>ostream</code> object we're referring to, it can set the width in that object.
<p>
Next, it must be possible to use the manipulator in an insertion
sequence. This implies that the <a name="an1306"></a>
return value of the manipulator must be
a <a name="an1307"></a>
reference to an <a name="an1308"></a>
<code>ostream</code> object also.
<p>
From the above considerations we're now able to construct our <code>w10</code>
function:
        <pre>
    #include &lt;ostream&gt;
    #include &lt;iomanip&gt;

    std::ostream &amp;w10(std::ostream &amp;str)
    {
        return str &lt;&lt; std::setw(10);
    }
</pre>
    The <code>w10</code> function can of course be used in a `stand alone' mode, but it
can also be used as a manipulator. E.g.,
    <pre>
        #include &lt;iostream&gt;
        #include &lt;iomanip&gt;

        using namespace std;

        extern ostream &amp;w10(ostream &amp;str);

        int main()
        {
            w10(cout) &lt;&lt; 3 &lt;&lt; " ships sailed to America" &lt;&lt; endl;
            cout &lt;&lt; "And " &lt;&lt; w10 &lt;&lt; 3 &lt;&lt; " more ships sailed too." &lt;&lt; endl;
        }
</pre>
        The <code>w10</code> function can be used as a manipulator because the <code>class
ostream</code> <a name="an1309"></a>
 has an overloaded <code>operator</code><<<code>()</code>
accepting a <a name="an1310"></a>
pointer to a function expecting an <code>ostream &amp;</code> and returning
an <code>ostream &amp;</code>. Its definition is:
        <pre>
    ostream&amp; operator&lt;&lt;(ostream &amp; (*func)(ostream &amp;str))
    {
        return (*func)(*this);
    }
</pre>
<p>
The above procedure does not work for <a name="an1311"></a>
manipulators requiring arguments:
it is of course possible to overload <code>operator</code><<<code>()</code> to accept an
<code>ostream</code> reference and the address of a function expecting an <code>ostream &amp;</code>
and, e.g., an <code>int</code>, but while the address of such a function may be
specified with the <<-operator, the arguments itself cannot be
specified. So, one wonders how the following construction has been
implemented:
        <pre>
    cout &lt;&lt; setprecision(3)
</pre>
    In this case the manipulator is defined as a <a name="an1312"></a>
macro. Macro's, however,
are the realm of the <a name="an1313"></a>
preprocessor, and may easily suffer from unwanted
<a name="an1314"></a>
side-effects. In <strong>C++</strong> programs they should be avoided whenever
possible. The following section introduces a way to implement manipulators
requiring arguments without resorting to macros, but using
    <a name="an1315"></a>
anonymous objects.
<p>
<a name="l160"></a>
<strong>9.10.1.1: Manipulators requiring arguments</strong>
        <a name="overloading/argmanipulators"></a>Manipulators taking arguments are implemented as <a name="an1316"></a>
 macros: they are
handled by the <a name="an1317"></a>
preprocessor, and are not available beyond the preprocessing
stage.  The problem appears to be that you can't call a function in an
<a name="an1318"></a>
insertion sequence: in a sequence of <code>operator</code><<<code>()</code> calls the compiler
will first call the functions, and then use their return values in the
insertion sequence. That will invalidate the ordering of the arguments passed
to your <<-operators.
<p>
So, one might consider constructing another overloaded <code>operator</code><<<code>()</code>
accepting the address of a function receiving not just the <a name="an1319"></a>
<code>ostream</code>
reference, but a series of other arguments as well. The problem now is that it
isn't clear how the function will receive its arguments: you can't just call
it, since that produces the abovementioned problem, and you can't just pass
its address in the insertion sequence, as you normally do with a
manipulator....
<p>
However, there is a solution, based on the use of <a name="an1320"></a>

anonymous objects:
    <ul>
    <li> First, a class is constructed, e.g. <code>Align</code>, whose
<a name="an1321"></a>
constructor expects multiple arguments. In our example representing,
respectively, the field width and the alignment.
    <li> Furthermore, we define the function:
            <pre>
        ostream &amp;operator&lt;&lt;(ostream &amp;ostr, Align const &amp;align)
</pre>
        so we can insert an <code>Align</code> object into the ostream.
    </ul>
    Here is an example of a little program using such a <em>home-made</em>
manipulator expecting multiple arguments:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;iomanip&gt;

    class Align
    {
        unsigned d_width;
        std::ios::fmtflags d_alignment;

        public:
            Align(unsigned width, std::ios::fmtflags alignment);
            std::ostream &amp;operator()(std::ostream &amp;ostr) const;
    };

        Align::Align(unsigned width, std::ios::fmtflags alignment)
        :
            d_width(width),
            d_alignment(alignment)
        {}

        std::ostream &amp;Align::operator()(std::ostream &amp;ostr) const
        {
            ostr.setf(d_alignment, std::ios::adjustfield);
            return ostr &lt;&lt; std::setw(d_width);
        }

    std::ostream &amp;operator&lt;&lt;(std::ostream &amp;ostr, Align const &amp;align)
    {
        return align(ostr);
    }

    using namespace std;

    int main()
    {
        cout
            &lt;&lt; "`" &lt;&lt; Align(5, ios::left) &lt;&lt; "hi" &lt;&lt; "'"
            &lt;&lt; "`" &lt;&lt; Align(10, ios::right) &lt;&lt; "there" &lt;&lt; "'" &lt;&lt; endl;
    }

    /*
        Generated output:

        `hi   '`     there'
    */
</pre>
    Note that in order to insert an anonymous <code>Align</code> object into the
<code>ostream</code>, the <code>operator</code><<<code>()</code> function <em>must</em> define a <code>Align const &amp;</code>
parameter (note the <code>const</code> modifier).
<p>
<a name="OverloadableOperators"></a><a name="l161"></a>
<h2>9.11: Overloadable operators</h2>
<a name="overloading/overloadable"></a>The following <a name="an1322"></a>
 operators can be overloaded:
        <pre>
    +       -       *       /       %       ^       &amp;       |
    ~       !       ,       =       &lt;       &gt;       &lt;=      &gt;=
    ++      --      &lt;&lt;      &gt;&gt;      ==      !=      &amp;&amp;      ||
    +=      -=      *=      /=      %=      ^=      &amp;=      |=
    &lt;&lt;=     &gt;&gt;=     []      ()      -&gt;      -&gt;*     new     new[]
    delete  delete[]
</pre>
    When `textual' alternatives of operators are available (e.g., <code>and</code> for
<code>&amp;&amp;</code>) then they are overloadable too.
<p>
Several of these operators may only be overloaded as member functions
    <a name="an1323"></a>
 <em>within</em> a class. This
holds true for the <code>'='</code>, the <code>'[]'</code>, the <code>'()'</code> and the <code>'-&gt;'</code>
operators. Consequently, it isn't possible to redefine, e.g., the assignment
operator globally in such a way that it accepts a <code>char const *</code> as an
<code>lvalue</code> and a <code>String &amp;</code> as an <em>rvalue</em>. Fortunately, that isn't
necessary either, as we have seen in section <a href="cplusplus09.html#ConversionOperators">9.3</a>.
<p>
Finally, the following operators are not overloadable at all:
        <pre>
    .       .*      ::      ?:      sizeof  typeid
</pre>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus08.html">Previous Chapter</a>
    <li> <a href="cplusplus10.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
